<script setup lang="ts">
import { onMounted } from 'vue'
import { loginThirdparty } from '@/api/user'
import { ref } from 'vue'
import { showSuccessToast, type FieldRule, type FormInstance } from 'vant'
import { getCode, loginBinding } from '@/api/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
/*
 手机验证码
 1：表单验证
    a:表单元素值的绑定
    b:定义规则
    c:绑定规则
    d:调用局部表单验证方法
 2：调用接口获取验证码
 3：倒计时处理

*/
const store = useUserStore()
const router = useRouter()
const formVal = ref({
  mobile: '',
  code: '',
  openId: ''
})
const rules = {
  mobile: [
    { required: true, message: '必填', trigger: 'onChange' },
    { pattern: /^1[3-9]\d{9}$/, message: '请正确输入手机号', trigger: 'onChange' }
  ] as FieldRule[],
  code: [
    { required: true, message: '必填', trigger: 'onChange' },
    { pattern: /^\d{6}$/, message: '请正确输入验证码', trigger: 'onChange' }
  ] as FieldRule[]
}
const form = ref<FormInstance>()
const time = ref(0)
let timeId = -1
const sendCodeEvent = async () => {
  // 局部表单验证
  await form.value?.validate('mobile')
  // 不管接口调用成功或者失败都来倒计时
  const res = await getCode({
    mobile: formVal.value.mobile,
    type: 'bindMobile'
  })
  showSuccessToast(res.data.code)
  // 只有成功才倒计时
  time.value = 60
  clearInterval(timeId)
  timeId = setInterval(() => {
    time.value--
    if (time.value <= 0) {
      clearInterval(timeId)
    }
  }, 1000)
}
//
/*
绑定手机号
1：完成表单验证（手机号+验证码）
2：定义接口api
3:导入接口api
4:在表单验证通过后调用api
5:调用成功
   提示
   存储它的用户信息(token)
   跳转页面
*/

const submit = async () => {
  await form.value?.validate()
  const res = await loginBinding(formVal.value)
  showSuccessToast('绑定成功')
  store.setUserInfo(res.data)
  // a==b(router.replace('/c'))===c    c===a    router.back()
  router.replace(store.backUrl || '/')
  console.log('绑定接口调用', res)
}

// 拿到openid
const isNeedBind = ref(false)
onMounted(() => {
  // this.$message()  this.$message.success()
  if (window.QC.Login.check()) {
    // 登录了
    window.QC.Login.getMe(async openId => {
      formVal.value.openId = openId
      console.log('openid', openId)
      try {
        const res = await loginThirdparty({
          openId: openId,
          source: 'qq'
        })
        // 成功
        console.log('登录返回值', res)
        store.setUserInfo(res.data)
        router.replace(store.backUrl || '/')
      } catch {
        // 登录失败
        isNeedBind.value = true
      }
    })
  }
})
</script>

<template>
  <div class="login-page" v-if="isNeedBind">
    <cp-nav-bar></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" ref="form">
      <van-field
        name="mobile"
        placeholder="请输入手机号"
        v-model="formVal.mobile"
        :rules="rules.mobile"
      ></van-field>
      <van-field name="code" placeholder="请输入验证码" v-model="formVal.code" :rules="rules.code">
        <template #button>
          <span class="btn-send" @click="sendCodeEvent" v-if="time === 0">发送验证码</span>
          <span class="btn-send" v-else>倒计时:{{ time }}s</span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit" @click="submit">
          立即绑定
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
.login {
  &-page {
    padding-top: 46px;
  }
  &-head {
    padding: 30px 30px 50px;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: normal;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  &-other {
    margin-top: 60px;
    padding: 0 30px;
    .icon {
      display: flex;
      justify-content: center;
      img {
        width: 36px;
        height: 36px;
        padding: 4px;
      }
    }
  }
}
.van-form {
  padding: 0 14px;
  .cp-icon {
    margin-right: 10px;
  }
  .cp-cell {
    height: 52px;
    line-height: 24px;
    padding: 14px 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .van-checkbox {
      a {
        color: var(--cp-primary);
        padding: 0 5px;
      }
    }
  }
  .btn-send {
    color: var(--cp-primary);
    &.active {
      color: rgba(22, 194, 163, 0.5);
    }
  }
}
</style>
